/*
 * @Author: your name
 * @Date: 2020-05-23 09:07:49
 * @LastEditTime: 2020-05-23 17:21:20
 * @LastEditors: OBKoro1
 * @Description: In User Settings Edit
 * @FilePath: \qianmingtian.github.io\code\java\SingleInstance.java
 */

public class SingleInstance {
    static class Resource {
        Resource(String str) {
            System.out.println("file " + str);
        }

    }

    /**
     * 使用枚举是实现单例的最好的方式,其次还有:二次加锁,常量....
     */
    private enum createSingleInstance {
        INSTANCE;

        private final Resource res;

        createSingleInstance() {
            res = new SingleInstance.Resource("1");
        }

        public Resource getInstance() {
            return res;
        }

    }

    public static void main(final String[] args) {
        Resource singleResource = createSingleInstance.INSTANCE.getInstance();
        Resource singleResource2 = createSingleInstance.INSTANCE.getInstance();

        if (singleResource == singleResource2) {
            System.out.println("they are ==, show that this object are single");
        } else if (singleResource.equals(singleResource2)) {
            System.out.println("they are equal");
        }
        /**
         * 常量是可以先定义,在被赋值,但是也只能是赋值一次
         */
        final int CONSTANT;
        CONSTANT = 1;
        if (CONSTANT == 1) {
            // CONSTANT =3;
            System.out.println("constant only can init one time");
        }

        /**
         * 字符应用testStrDouble被重新赋值的时候,原始字符串(存放在堆栈中)会被内存回收机制自动回收
         */
        String testStrDouble = "test";
        System.out.println(testStrDouble);
        testStrDouble = "double";
        System.out.println(testStrDouble.getClass());

    }
}